package web.controller.admin;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import com.alibaba.fastjson.JSON;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

import core.Const;
import kit.EhCacheKit;
import kit.StringUtil;
import plugin.route.ControllerBind;
import web.common.BaseController;
import web.common.JsonEntity;
import web.common.enums.ResultCodeEnum;
import web.model.RolePermissions;
import web.model.Roles;
import web.model.temp.VoZtree;
import web.service.PermissionsService;
/**
 * 角色配置
 * 
 */
@ControllerBind(controllerKey = "/admin/roles")
public class RolesController extends BaseController {

	private static final String path = "roles_";
	private final static String CONTROLLER_KEY = "/admin/roles";
	private static PermissionsService permissionsService = new PermissionsService();

	@RequiresPermissions("admin:roles:list")
	public void list() {
		Roles model = getModel(Roles.class,"attr");
		int pageindex = getParaToInt("page", 1);
		StringBuilder sql  = new StringBuilder("FROM roles  where 1=1 ");
		sql.append("ORDER BY create_time DESC");
		Page<Roles> page = Roles.dao.paginate(pageindex, Const.PAGE_SIZE, "SELECT *",
				sql.toString());
		setAttr("page", page);
		setAttr("attr", model);
		render(path + "list.ftl");
	}

	@RequiresPermissions("admin:roles:add")
	public void add() {
		render(path + "add.ftl");
	}

	public void view() {
		Roles model = Roles.dao.findById(getParaToInt());
		setAttr("model", model);
		render(path + "view.ftl");
	}

	@RequiresPermissions("admin:roles:del")
	public void delete() {
		int id = getParaToInt(0, 0);
		if (id != 0) {
			boolean r = new Roles().deleteById(id);
			if (r) {
				EhCacheKit.cleanRoleAndPerm();
				sendAlert("删除成功", CONTROLLER_KEY + "/list");
			} else {
				sendAlert("删除失败", CONTROLLER_KEY + "/list");
			}
		} else {
			sendAlert("删除失败", CONTROLLER_KEY + "/list");
		}
	}

	@RequiresPermissions("admin:roles:edit")
	public void edit() {
		int id = getParaToInt(0, 0);
		if (id > 0) {
			Roles model = Roles.dao.findById(id);
			setAttr("model", model);
			render(path + "edit.ftl");
		} else {
			sendAlert("操作失败:未找到id", CONTROLLER_KEY + "/list");
		}
	}

	@RequiresPermissions(value = { "admin:roles:add", "admin:roles:edit" }, logical = Logical.OR)
	public void save() {
		Integer pid = getParaToInt();
		Roles model = getModel(Roles.class,"model");
		boolean result =false;
		if (pid != null && pid > 0) { // 更新
			result =	model.update();
		} else { // 新增
			model.remove("id");
			result=	model.save();
		}

		if (result) {
			EhCacheKit.cleanRoleAndPerm();
			sendAlert("保存成功", CONTROLLER_KEY + "/list");
		} else {
			sendAlert("保存失败", CONTROLLER_KEY + "/list");
		}
	}

	@RequiresPermissions("admin:roles:perm")
	public void perm() {
		int id = getParaToInt(0, 0);
		if (id > 0) {
			List<RolePermissions> rolePermissions = RolePermissions.dao
					.find("select * from role_permissions where role_id=?", id);
			Set<Long> permIdSet = new HashSet<>();
			for (RolePermissions rolePermissions2 : rolePermissions) {
				permIdSet.add(rolePermissions2.getPermissionsId());
			}
			List<VoZtree> znodes = permissionsService.getVoZtreeList();
			List<VoZtree> nodeList = new ArrayList<VoZtree>();
			for (VoZtree node1 : znodes) {
				boolean mark = false;
				if (permIdSet.contains(node1.getId())) {
					node1.setChecked(true);
				}
				for (VoZtree node2 : znodes) {
					if (node1.getPid() == node2.getId()) {
						mark = true;
						if (node2.getChildren() == null)
							node2.setChildren(new ArrayList<VoZtree>());
						node2.getChildren().add(node1);
						break;
					}
				}
				if (!mark) {
					nodeList.add(node1);
				}
			}
			setAttr("roleid", id);
			setAttr("znodes", JSON.toJSONString(nodeList));
			render(path + "perm.ftl");
		} else {
			sendAlert("查看失败,id不能为空", CONTROLLER_KEY + "/list");
		}
	}
	
	/**
	* @Title: addperm
	* @Description: 角色权限编辑
	* @author yangyw
	* @throws
	*/
	public void addperm(){
		int roleid = getParaToInt("roleid", 0);
		String perms = getPara("perms");
		String[] permArray = StringUtil.split(perms, ",");
		JsonEntity json = new JsonEntity<>();
		if (roleid != 0) {
			int i = Db.update("DELETE FROM `role_permissions` WHERE `role_id`=?", roleid);
			if (permArray != null && permArray.length > 0) {
				List<String> sqlList = new ArrayList<>();
				for (String perm : permArray) {
					int p = NumberUtils.toInt(perm);
					if (p > 0) {
						sqlList.add("INSERT INTO `role_permissions` (`role_id`, `permissions_id`) VALUES ('" + roleid
								+ "', '" + p + "')");
					}
				}
				Db.batch(sqlList, 10);
				EhCacheKit.cleanRoleAndPerm();

				renderJson(json);
			} else {
				renderJson(json);
			}
		} else {
			json.setJsonEntity(ResultCodeEnum.ERROR);
			json.setMsg("角色id不能为空");
			renderJson(json);
		}

	}
}
